package com.atguigu.paymentdemo.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class OkHttpGetRequest {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        String bxmid= "20241124110450630000023281231241";
        String url=String.format("https://openlog.bianxianmao.com/inads/s.gif?mt=8&bxmid=%s&conversion_type=5", bxmid);


        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 对于GET请求，通常不需要处理响应体（例如，这是一个图像URL）
            // 你可以打印响应代码或者响应头信息
            System.out.println("Response Code: " + response.code());
            System.out.println("Response Headers: " + response.headers().toString());

            // 如果需要，可以读取响应体（但请注意，对于图像或其他二进制数据，处理方式会有所不同）
            // String responseBody = response.body().string();
            // System.out.println("Response Body: " + responseBody);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String okhttpGet(String bxmid) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        OkHttpClient client = new OkHttpClient();

        Long time = System.currentTimeMillis();
        String url=String.format("https://openlog.bianxianmao.com/inads/s.gif?mt=8&bxmid=%s&conversion_type=5", bxmid);
        log.info("开始时间:{} 请求地址:{}",df.format(new Date()) , url );

        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // 对于GET请求，通常不需要处理响应体（例如，这是一个图像URL）
            // 你可以打印响应代码或者响应头信息
            log.info("Response Code: " + response.code()+"耗时:"+(System.currentTimeMillis()-time));
//            System.out.println("Response Code: " + response.code());
//            System.out.println("Response Headers: " + response.headers().toString());

            // 如果需要，可以读取响应体（但请注意，对于图像或其他二进制数据，处理方式会有所不同）
            // String responseBody = response.body().string();
            // System.out.println("Response Body: " + responseBody);

            return Integer.toString(response.code());
        } catch (IOException e) {
            log.error("请求变现猫失败:{},{}",e.getMessage(),url);
            e.printStackTrace();
            return "-1";
        }
    }
}
